package day38.zuoye;

public class Person implements Cloneable{
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 重写clone()方法
    protected Person clone() {
        try {
            return (Person) super.clone();
        } catch (CloneNotSupportedException e) {
            // 处理异常
            return null;
        }
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

class Main {
    public static void main(String[] args) {
        Person person1 = new Person("John", 25);

        // 使用clone()方法创建person2对象的副本
        Person person2 = person1.clone();

        // 验证副本是否成功创建
        System.out.println(person1.getName());  // 输出：John
        System.out.println(person1.getAge());   // 输出：25
        System.out.println(person2.getName());  // 输出：John
        System.out.println(person2.getAge());   // 输出：25

        // 修改person2的属性

        person2.setName("Mike");
        person2.setAge(30);

        System.out.println("验证person1和person2是否相互独立");
        System.out.println(person1.getName());  // 输出：John
        System.out.println(person1.getAge());   // 输出：25
        System.out.println(person2.getName());  // 输出：Mike
        System.out.println(person2.getAge());   // 输出：30
    }
}
